<template>
  <view class="dynamic-form__control">
    <uni-forms-item
      class="tui-input-item"
      v-if="['text', 'textarea', 'password', 'number', 'idcard', 'digit'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <uni-easyinput
        :type="control.columnFormat"
        :placeholder="control.placeholder"
        v-model="val"
        @input="handleInput"
        :disabled="disabled"
        :maxlength="control.maxLength"
        clearable
      />
    </uni-forms-item>
    <uni-forms-item
      v-else-if="['combo'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <view class="dynamic-form__disabled" v-if="disabled">{{ val }}</view>
      <uni-data-picker
        v-else
        :popup-title="`请选择${control.columnDesc}`"
        :localdata="promptList"
        v-model="val"
        @change="handleChange"
        :disabled="disabled"
      >
      </uni-data-picker>
    </uni-forms-item>
    <uni-forms-item
      v-else-if="['date'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <view class="dynamic-form__disabled" v-if="disabled">{{ val }}</view>
      <uni-datetime-picker v-else type="date" v-model="val" @change="handleChange" return-type="timestamp" :disabled="disabled">
      </uni-datetime-picker>
    </uni-forms-item>
    <uni-forms-item
      v-else-if="['check'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <uni-data-checkbox multiple :localdata="promptList" v-model="val" @change="handleChange" :disabled="disabled">
      </uni-data-checkbox>
    </uni-forms-item>
    <uni-forms-item
      v-else-if="['radio'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <uni-data-checkbox :localdata="promptList" v-model="val" @change="handleChange" :disabled="disabled">
      </uni-data-checkbox>
    </uni-forms-item>
    <!-- <uni-forms-item
      v-else-if="['attachment'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <AttachmentDownload :attachmentList="val" v-if="disabled" />
      <uni-file-picker
        v-else
        ref="uploadFilePicker"
        :value="val"
        :limit="control.limit || '5'"
        file-mediatype="all"
        :auto-upload="false"
        @progress="onProgress"
        @success="onSuccess"
        @fail="onFail"
        @select="onSelect"
        @delete="onDelete"
        :readonly="disabled"
      >
      </uni-file-picker>
    </uni-forms-item> -->
    <uni-forms-item
      v-else-if="['attachment'].includes(control.columnFormat)"
      :name="control.columnName"
      :label="control.columnDesc"
      :required="JSON.parse(control.ismust)"
    >
      <!-- limit:1表示单文件上传，且为object格式，大于1为多文件上传，且为array格式，limit最大为9 -->
      <AttachmentDownload :attachmentList="val" v-if="disabled" />
      <uni-file-picker
        v-else
        ref="uploadFilePicker"
        :value="val"
        :limit="control.limit || 5"
        file-mediatype="image"
        :auto-upload="false"
        @progress="onProgress"
        @success="onSuccess"
        @fail="onFail"
        @select="onSelect"
        @delete="onDelete"
        :readonly="disabled"
      >
      </uni-file-picker>
    </uni-forms-item>
  </view>
</template>

<script>
import UniDataCheckbox from '../uni-data-checkbox/uni-data-checkbox'
import UniDataPicker from '../uni-data-picker/uni-data-picker'
import UniDatetimePicker from '../uni-datetime-picker/uni-datetime-picker'
import UniEasyinput from '../uni-easyinput/uni-easyinput'
import UniFilePicker from '../uni-file-picker/uni-file-picker'
import UniFormsItem from '../uni-forms-item/uni-forms-item'
import uploadFile from './uploadFile'
import AttachmentDownload from './attachmentDownload'
import {requestProtocol, domain} from '@/common/constant.js'
export default {
  props: {
    control: {
      type: Object,
      default: () => ({}),
    },
    value: {
      type: [String, Number, Boolean, Object, Array, null, undefined],
    },
  },
  data() {
    return {
      val: this.value,
    }
  },
  components: {
    UniDataCheckbox,
    UniDataPicker,
    UniDatetimePicker,
    UniEasyinput,
    UniFilePicker,
    UniFormsItem,
    AttachmentDownload,
  },
  computed: {
    promptList() {
      if (['combo', 'radio', 'check'].includes(this.control.columnFormat)) {
        return Array.isArray(this.control.promptList) && this.control.promptList.map((item) => ({
          value: item.key,
          text: item.value,
          disabled: this.disabled,
        }))
      }
    },
    disabled() {
      return this.$parent.$parent.disabled || JSON.parse(this.control.isReadOnly)
    },
  },
  created() {},
  methods: {
    handleInput(value) {
      this.$emit('input', value)
      //this.$emit('change', value)
    },
    handleChange(e) {
      let value = null
      let control = this.control
      let type = control.columnFormat
      if (type === 'combo') {
        value = e.detail.value[0].value
      } else if (type === 'check' || type === 'radio') {
        value = e.detail.value
      } else if (type === 'date') {
        console.log(e)
        value = e
      }
      this.$emit('input', value)
      this.$emit('change', {
        name: control.columnName,
        value,
      })
    },
    onFail() {},
    async onSelect({ tempFiles }) {
      console.log('select', tempFiles)
      if (tempFiles.length > 0) {
        const fileArr = tempFiles.map(({ name, extname, url }) => ({
          name,
          extname,
          url,
        }))
        if (!Array.isArray(this.val)) {
          this.val = []
          console.error(`请检查${this.control.columnDesc}的${this.control.columnFormat}`)
        }
        this.val = this.val.concat(fileArr)
        const fileNoArr = await this.handleUploadFile(fileArr.map((file) => file.url))
        this.$emit(
          'input',
          this.val.map((file, index) => ({
            ...file,
            fileNo: fileNoArr[index],
          }))
        )
      }
    },
    onDelete(e) {
      this.val = this.val.filter((img) => img.name !== e.tempFile.name)
      this.$emit('input', this.val)
    },
    async handleUploadFile(files) {
      const uploadResult = await uploadFile(`${requestProtocol}${domain}/smallapp/formController/uploadFiles`, files, {
        open_id: this.$parent.$parent.open_id,
        guid: this.control.guid,
      })
      const fileNoArr = uploadResult
        .flat()
        .filter(Boolean)
        .map((item) => {
          if (item) {
            return JSON.parse(item.data).fileNo
          }
        })
      return fileNoArr
    },
  },
}
</script>

<style lang="scss">
.dynamic-form__control {
  background-color: #ffffff;
}
.dynamic-form__disabled {
  height: 100%;
  display: flex;
  align-items: center;
}
</style>
